package config

import (
	"encoding/json"
	"io"
	"os"
)

// 配置
type Config struct {
	Database struct {
		Host     string
		Port     string
		User     string
		Password string
		DBName   string
	}
	IxBrowser struct {
		// API URLs
		CreateGroupURL        string // 创建分组API
		CopyBrowserURL        string // 复制浏览器API
		CreateEmployeeURL     string // 创建员工API
		FindEmployeeURL       string // 查找员工API
		UpdateEmployeeURL     string // 更新员工分组API
		DeleteEmployeeURL     string // 删除员工API
		DeleteGroupURL        string // 删除分组API
		DeleteBrowserURL      string // 删除浏览器API
		GetGroupBrowsersURL   string // 获取分组内浏览器列表API
		SecToken              string // 安全令牌
		Token                 string // 授权令牌
		GetBrowserListURL     string // 获取浏览器列表API
		CreateProxyURL        string // 创建代理API
		UpdateProxyURL        string // 更新代理API
		DeleteProxyURL        string // 删除代理API
		GetProxyListURL       string // 获取代理列表API
		CreateBrowserURL      string // 创建浏览器API
		UpdateBrowserURL      string // 更新浏览器API
		UpdateBrowserProxyURL string // 更新浏览器代理API
		GetTagListURL         string // 获取标签列表API
	}
	Server struct {
		Port string
	}
}

// 全局配置实例
var AppConfig = &Config{}

// 从环境变量加载配置
func loadFromEnv(config *Config) {
	// 数据库配置
	if val := os.Getenv("DB_HOST"); val != "" {
		config.Database.Host = val
	}
	if val := os.Getenv("DB_PORT"); val != "" {
		config.Database.Port = val
	}
	if val := os.Getenv("DB_USER"); val != "" {
		config.Database.User = val
	}
	if val := os.Getenv("DB_PASSWORD"); val != "" {
		config.Database.Password = val
	}
	if val := os.Getenv("DB_NAME"); val != "" {
		config.Database.DBName = val
	}

	// IxBrowser配置
	if val := os.Getenv("IX_CREATE_GROUP_URL"); val != "" {
		config.IxBrowser.CreateGroupURL = val
	}
	if val := os.Getenv("IX_COPY_BROWSER_URL"); val != "" {
		config.IxBrowser.CopyBrowserURL = val
	}
	if val := os.Getenv("IX_CREATE_EMPLOYEE_URL"); val != "" {
		config.IxBrowser.CreateEmployeeURL = val
	}
	if val := os.Getenv("IX_FIND_EMPLOYEE_URL"); val != "" {
		config.IxBrowser.FindEmployeeURL = val
	}
	if val := os.Getenv("IX_UPDATE_EMPLOYEE_URL"); val != "" {
		config.IxBrowser.UpdateEmployeeURL = val
	}
	if val := os.Getenv("IX_DELETE_EMPLOYEE_URL"); val != "" {
		config.IxBrowser.DeleteEmployeeURL = val
	}
	if val := os.Getenv("IX_DELETE_GROUP_URL"); val != "" {
		config.IxBrowser.DeleteGroupURL = val
	}
	if val := os.Getenv("IX_DELETE_BROWSER_URL"); val != "" {
		config.IxBrowser.DeleteBrowserURL = val
	}
	if val := os.Getenv("IX_GET_GROUP_BROWSERS_URL"); val != "" {
		config.IxBrowser.GetGroupBrowsersURL = val
	}
	if val := os.Getenv("IX_SEC_TOKEN"); val != "" {
		config.IxBrowser.SecToken = val
	}
	if val := os.Getenv("IX_TOKEN"); val != "" {
		config.IxBrowser.Token = val
	}
	if val := os.Getenv("IX_GET_BROWSER_LIST_URL"); val != "" {
		config.IxBrowser.GetBrowserListURL = val
	}
	if val := os.Getenv("IX_CREATE_PROXY_URL"); val != "" {
		config.IxBrowser.CreateProxyURL = val
	}
	if val := os.Getenv("IX_UPDATE_PROXY_URL"); val != "" {
		config.IxBrowser.UpdateProxyURL = val
	}
	if val := os.Getenv("IX_DELETE_PROXY_URL"); val != "" {
		config.IxBrowser.DeleteProxyURL = val
	}
	if val := os.Getenv("IX_GET_PROXY_LIST_URL"); val != "" {
		config.IxBrowser.GetProxyListURL = val
	}
	if val := os.Getenv("IX_CREATE_BROWSER_URL"); val != "" {
		config.IxBrowser.CreateBrowserURL = val
	}
	if val := os.Getenv("IX_UPDATE_BROWSER_URL"); val != "" {
		config.IxBrowser.UpdateBrowserURL = val
	}
	if val := os.Getenv("IX_UPDATE_BROWSER_PROXY_URL"); val != "" {
		config.IxBrowser.UpdateBrowserProxyURL = val
	}
	if val := os.Getenv("IX_GET_TAG_LIST_URL"); val != "" {
		config.IxBrowser.GetTagListURL = val
	}

	// 服务器配置
	if val := os.Getenv("SERVER_PORT"); val != "" {
		config.Server.Port = val
	}
}

// 从文件加载配置
func loadFromFile(config *Config, path string) error {
	// 如果文件不存在，直接返回
	if _, err := os.Stat(path); os.IsNotExist(err) {
		return nil
	}

	file, err := os.Open(path)
	if err != nil {
		return err
	}
	defer file.Close()

	data, err := io.ReadAll(file)
	if err != nil {
		return err
	}

	return json.Unmarshal(data, config)
}

// 初始化配置
func Init() error {
	// 设置默认值
	AppConfig = &Config{
		Database: struct {
			Host     string
			Port     string
			User     string
			Password string
			DBName   string
		}{
			Host:     "localhost",
			Port:     "3306",
			User:     "root",
			Password: "password",
			DBName:   "ixbrowser",
		},
		IxBrowser: struct {
			CreateGroupURL        string
			CopyBrowserURL        string
			CreateEmployeeURL     string
			FindEmployeeURL       string
			UpdateEmployeeURL     string
			DeleteEmployeeURL     string
			DeleteGroupURL        string
			DeleteBrowserURL      string
			GetGroupBrowsersURL   string
			SecToken              string
			Token                 string
			GetBrowserListURL     string
			CreateProxyURL        string
			UpdateProxyURL        string
			DeleteProxyURL        string
			GetProxyListURL       string
			CreateBrowserURL      string
			UpdateBrowserURL      string
			UpdateBrowserProxyURL string
			GetTagListURL         string
		}{
			CreateGroupURL:        "http://localhost:8081/add-group",
			CopyBrowserURL:        "http://localhost:8081/profile-copy",
			CreateEmployeeURL:     "http://localhost:8081/api/create-register",
			FindEmployeeURL:       "http://localhost:8081/get-user-list",
			UpdateEmployeeURL:     "http://localhost:8081/api/update-team-member",
			DeleteEmployeeURL:     "http://localhost:8081/api/delete-team-member",
			DeleteGroupURL:        "http://localhost:8081/group-delete",
			DeleteBrowserURL:      "http://localhost:8081/profile-delete",
			GetGroupBrowsersURL:   "http://localhost:8081/profile-list",
			CreateProxyURL:        "http://localhost:8081/proxy-create",
			UpdateProxyURL:        "http://localhost:8081/proxy-update",
			DeleteProxyURL:        "http://localhost:8081/proxy-delete",
			GetProxyListURL:       "http://localhost:8081/proxy-list",
			CreateBrowserURL:      "http://localhost:8081/browser-create",
			UpdateBrowserURL:      "http://localhost:8081/browser-update",
			UpdateBrowserProxyURL: "http://localhost:8081/browser-proxy-update",
			GetTagListURL:         "http://localhost:8081/tag-list",
			SecToken:              "",
			Token:                 "",
			GetBrowserListURL:     "",
		},
		Server: struct {
			Port string
		}{
			Port: "8080",
		},
	}

	// 尝试从配置文件加载
	configPath := os.Getenv("CONFIG_FILE")
	if configPath == "" {
		configPath = "config.json" // 默认配置文件路径
	}

	// 加载配置文件（如果存在）
	if err := loadFromFile(AppConfig, configPath); err != nil {
		return err
	}

	// 环境变量优先级高于配置文件
	loadFromEnv(AppConfig)

	return nil
}
